package com.example.event;

import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import com.example.entity.DbBlockDto;
import com.example.entity.GatherData;
import com.example.exception.OpcException;
import com.example.kafka.PCLKafkaService;
import com.example.service.GatherDataService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;

/**
 * Copyright: Copyright (c) 2022
 *
 * <p>
 * Description:
 *
 * @author LiuFeng
 * @version 2022/12/5 14:56
 * @since
 */
@Configuration
@Slf4j
@EnableAsync
public class EventListenerConfig {

    @Resource
    private PCLKafkaService kafkaService;

    private ObjectMapper mapper;

    @PostConstruct
    public void init() {
        mapper = new ObjectMapper();
    }

    @Async
    @EventListener
    public void handleEvent(OpcMessageEvent event) {
        String message = getMessage(event.getDto());
        kafkaService.sendMessage(message);
    }

    private String getMessage(List<DbBlockDto> dto) {
        try {
            return mapper.writeValueAsString(dto);
        } catch (JsonProcessingException ex) {
            throw new OpcException(ex);
        }
    }

}
